﻿using AutoMapper;
using Common.Enum;
using Entity.ERP.DTO.SaleOrder;
using Entity.ERP.Entity;
using Entity.ERP.View.SaleOrder;
using Entity.ERP.View.SaleOrderItem;
using FrameWork.DataContext;
using FrameWork.DataHelper;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace Service.ERP
{
    public class SaleOrderService
    {
        /**
         * 数据库
         */
        private readonly DataContext _context;

        /**
         * 自动映射
         */
        private readonly IMapper _mapper;

        /**
         * 构造注入
         */
        public SaleOrderService(DataContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        /**
         * 获取销售订单列表
         */
        public async Task<RequestResponseModel<PageResult<SaleOrderView>>> GetSaleOrderList(SaleOrderSearchDTO saleOrderSearchDTO)
        {
            //筛选
            var query = _context.SaleOrderView
                .WhereIF(a => a.Code.Contains(saleOrderSearchDTO.Code), !string.IsNullOrEmpty(saleOrderSearchDTO.Code))
                .WhereIF(a => a.CardNo.Contains(saleOrderSearchDTO.CardNo), !string.IsNullOrEmpty(saleOrderSearchDTO.CardNo))
                .WhereIF(a => a.CustomerCode.Contains(saleOrderSearchDTO.Customer) || a.CustomerName.Contains(saleOrderSearchDTO.Customer) || a.CustomerPhone.Contains(saleOrderSearchDTO.Customer), !string.IsNullOrEmpty(saleOrderSearchDTO.Customer))
                .WhereIF(a => a.Status == saleOrderSearchDTO.Status, saleOrderSearchDTO.Status != null)
                .WhereIF(a => a.ExamStatus == saleOrderSearchDTO.ExamStatus, saleOrderSearchDTO.ExamStatus != null)
                ;

            //返回列表
            var saleOrderList = await query
                .Page(saleOrderSearchDTO.CurrentPage, saleOrderSearchDTO.PageSize)
                .ToListAsync();

            //计算总数
            var pageCount = await query.CountAsync();

            //返回数据
            var pageResult = new PageResult<SaleOrderView>(saleOrderList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 销售订单子单列表
         */
        public async Task<RequestResponseModel<PageResult<SaleOrderItemView>>> GetSaleOrderItemList(SaleOrderItemSearchDTO saleOrderItemSearchDTO)
        {
            //筛选
            var query = _context.SaleOrderItemView
                .Where(a => a.SaleOrderId == saleOrderItemSearchDTO.Id)
                ;

            //返回列表
            var saleOrderItemList = await query
                .Page(saleOrderItemSearchDTO.CurrentPage, saleOrderItemSearchDTO.PageSize)
                .ToListAsync();

            //计算总数
            var pageCount = await query.CountAsync();

            //返回数据
            var pageResult = new PageResult<SaleOrderItemView>(saleOrderItemList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 销售订单源单列表
         */
        public async Task<RequestResponseModel<PageResult<SaleOrderSourceView>>> GetSaleOrderSourceList(SaleOrderSourceSearchDTO saleOrderSourceSearchDTO)
        {
            //筛选
            var query = _context.SaleOrderSourceView
                .WhereIF(a => a.Code.Contains(saleOrderSourceSearchDTO.Code), !string.IsNullOrEmpty(saleOrderSourceSearchDTO.Code))
                .WhereIF(a => a.CardNo.Contains(saleOrderSourceSearchDTO.CardNo), !string.IsNullOrEmpty(saleOrderSourceSearchDTO.CardNo))
                .WhereIF(a => a.CustomerCode.Contains(saleOrderSourceSearchDTO.Customer) || a.CustomerName.Contains(saleOrderSourceSearchDTO.Customer) || a.CustomerPhone.Contains(saleOrderSourceSearchDTO.Customer), !string.IsNullOrEmpty(saleOrderSourceSearchDTO.Customer))
                .Where(a => a.ExamStatus == StateEnum.ExamStatus.审核通过)
                .Where(a => a.Status == StateEnum.SaleType.待生成)
                .Include(a => a.Items)
                ;

            //返回列表
            var saleOrderSourceList = await query
                .Page(saleOrderSourceSearchDTO.CurrentPage, saleOrderSourceSearchDTO.PageSize)
                .ToListAsync();

            //计算总数
            var pageCount = await query.CountAsync();

            //返回数据
            var pageResult = new PageResult<SaleOrderSourceView>(saleOrderSourceList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 新增销售订单
         */
        public async Task<RequestResponseModel<string>> AddSaleOrder(SaleOrderAddDTO saleOrderAddDTO)
        {
            //处理主单单据
            var saleOrder = _mapper.Map<SaleOrderModel>(saleOrderAddDTO);
            saleOrder.Id = Guid.NewGuid().ToString();
            saleOrder.Status = StateEnum.SaleType.待生成;
            saleOrder.ExamStatus = StateEnum.ExamStatus.待审核;
            saleOrder.CreateTime = DateTime.Now;

            //处理子单数据
            var saleOrderItemList = _mapper.Map<List<SaleOrderItemModel>>(saleOrderAddDTO.items);
            foreach (var item in saleOrderItemList)
            {
                item.Id = Guid.NewGuid().ToString();
                item.SaleOrderId = saleOrder.Id;
                item.CardNo = saleOrder.CardNo;
            }

            //修改并保存数据库
            _context.SaleOrder.Add(saleOrder);
            _context.SaleOrderItem.AddRange(saleOrderItemList);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "新增成功", saleOrder.Id);
        }

        /**
         * 编辑销售订单
         */
        public async Task<RequestResponseModel<string>> PutSaleOrder(SaleOrderUpdateDTO saleOrderUpdateDTO)
        {
            //校验id有效性
            var query = await Valid.ValidId(_context.SaleOrder, saleOrderUpdateDTO.Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "销售订单id无效", saleOrderUpdateDTO.Id);
            }

            //只有待审核的单据才能编辑
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的订单才能编辑", saleOrderUpdateDTO.Id);
            }

            //处理主单
            var saleOrder = _mapper.Map<SaleOrderModel>(saleOrderUpdateDTO);
            //处理子单
            var saleOrderItemList = _mapper.Map<List<SaleOrderItemModel>>(saleOrderUpdateDTO.items);

            //修改并保存数据库
            _context.SaleOrder.Update(saleOrder);
            _context.SaleOrderItem.UpdateRange(saleOrderItemList);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "更新成功", query.Id);
        }

        /**
         * 删除销售订单
         */
        public async Task<RequestResponseModel<string>> DeleteSaleOrder(string Id)
        {
            //校验id有效性
            var query = await Valid.ValidId(_context.SaleOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "id无效", Id);
            }

            //已审核的单据无法删除
            if (query.Status != StateEnum.SaleType.待生成)
            {
                return RequestResponse.CreateResponse(400, "只有待生成的单据才能删除", Id);
            }

            //查找该id下的子单
            var saleOrderItemList = _context.SaleOrderItem
                .Where(a => a.Id.Equals(Id));

            //操作数据库并保存
            _context.SaleOrder.Remove(query);
            _context.SaleOrderItem.RemoveRange(saleOrderItemList);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "删除成功", Id);
        }

        /**
         * 销售订单 - 审核通过
         */
        public async Task<RequestResponseModel<string>> PassSaleOrder(string Id)
        {
            //校验id
            var query = await Valid.ValidId(_context.SaleOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            //校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的单据才可以审核通过", Id);
            }

            //修改数据
            query.ExamStatus = StateEnum.ExamStatus.审核通过;

            //修改并保存数据库
            _context.SaleOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "审核通过成功", Id);
        }

        /**
         * 销售订单 - 审核不通过
         */
        public async Task<RequestResponseModel<string>> UnPassSaleOrder(string Id)
        {
            //校验id
            var query = await Valid.ValidId(_context.SaleOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            //校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的单据才可以审核不通过", Id);
            }

            //修改数据
            query.ExamStatus = StateEnum.ExamStatus.审核不通过;

            //修改并保存数据库
            _context.SaleOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "审核不通过成功", Id);
        }

        /**
         * 销售订单 - 反审核
         */
        public async Task<RequestResponseModel<string>> CancelPassSaleOrder(string Id)
        {
            //校验id
            var query = await Valid.ValidId(_context.SaleOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            //校验状态
            if (query.Status != StateEnum.SaleType.待生成)
            {
                return RequestResponse.CreateResponse(400, "只有待生成的单据才可以反审核", Id);
            }

            //修改数据
            query.ExamStatus = StateEnum.ExamStatus.待审核;

            //修改并保存数据库
            _context.SaleOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "反审核成功", Id);
        }
    }
}
